using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using OpenComposite.EII.Repository;
using OpenComposite.Repository.Properties;

namespace OpenComposite.EII.RepositoryUIs
{
	public partial class FormCreateNewRule : FormCreateNewItem
	{
		#region Initialization
		public FormCreateNewRule(IServiceProvider serviceProvider, Repository.RepositoryItemBase item,
			bool bAllowContinue)
			: base(serviceProvider, item, bAllowContinue)
		{
			InitializeComponent();
			if ( this.RepositoryItem != null ) {
				this.Text = string.Format(Resources.msgCreateNew, this.RepositoryItem.RepositoryItemTypeName);
			}
			base.ShowAllDomains = false;
			base.AllowChangeDomain = false;
		}
		public FormCreateNewRule(IServiceProvider serviceProvider, Repository.RepositoryItemBase item,
			bool bAllowContinue, ItemType folderType)
			: base(serviceProvider, item, bAllowContinue, folderType)
		{
			InitializeComponent();
			if ( this.RepositoryItem != null ) {
				this.Text = string.Format(Resources.msgCreateNew, this.RepositoryItem.RepositoryItemTypeName);
			}
			base.ShowAllDomains = false;
			base.AllowChangeDomain = false;
		}
		#endregion

		#region Protected Members

		#region Methods
		// override
		protected override void OnValidateNewItem(CancelEventArgs e)
		{
			DataTable dt = Global.Data.SearchRepositoryItems(
				Global.Status.CurrentDomainId, this.RepositoryItem.RepositoryItemType,
				txtName.Text, null, true);
			if ( dt != null && dt.Rows.Count > 0 ) {
				bool foundInSamePolicy = false;
				foreach ( DataRow row in dt.Rows ) {
					DataTable dtParent = Global.Data.GetRepositoryParentsOfType(
						(ItemType)row["type"], (int)row["id"], ItemType.BPolicy);
					foreach ( DataRow rowParent in dtParent.Rows ) {
						if ( (ItemType)rowParent["parent_reptype_id"] == this.ParentItem.RepositoryItemType &&
							 (int)rowParent["parent_id"] == this.ParentItem.ID ) {
							foundInSamePolicy = true;
							goto ExitSearch;
						}
					}
				}
ExitSearch:
				if ( foundInSamePolicy ) {
					MessageBox.Show("A rule with this name exists in the current policy." + Environment.NewLine + Environment.NewLine +
									"Please enter an other name.",
									this.Text, MessageBoxButtons.OK, MessageBoxIcon.Stop);
					txtName.Focus();
					txtName.SelectAll();
					e.Cancel = true;
				}
			}
			//base.OnValidateNewItem(e);
		}
		#endregion

		#endregion

		#region Protected Members

		#region Event Handler
		private void txtName_KeyPress(object sender, KeyPressEventArgs e)
		{
			e.Handled = !Helpers.IsValidCharForName(e.KeyChar);
		}
		#endregion

		#endregion
	}
}